package com.dtranx.tools.licensecreate;

import com.dtranx.tools.licensecreate.utils.AESUtils;
import com.dtranx.tools.licensecreate.utils.Gqrq;

import javax.swing.*;
import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.event.*;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.Random;

import static com.dtranx.tools.licensecreate.test.CreateSign.createLicense;

public class CreateLicense {
    private JTextField macTextField;
    private JTextField cpuTextField;
    private JTextField areaTextField;
    private JTextField startTextField;
    private JTextField endTextField;
    private JTextField validateTextField;
    private JTextField versionTextField;
    private JTextField pathTextField;
    private JPanel jpanel;
    private JButton shengchengButton;
    private JButton chooseSDateButton;
    private JButton chooseEDateButton;
    private JButton chooseVDateButton;
    private JButton getMacButton;
    private JButton getCpuButton;
    private JButton getAreaButton;
    private JButton getVersionButton;
    private JButton getPathButton;
    private JTextField gqrqField;

    public static void main(String[] args) {
        JFrame frame = new JFrame("CreateLicense");
        frame.setSize(800, 600);
        frame.setContentPane(new CreateLicense().jpanel);
        // 设置默认关闭操作
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // 获取屏幕尺寸
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        int screenWidth = screenSize.width;
        int screenHeight = screenSize.height;

        // 获取JFrame的尺寸
        int frameWidth = frame.getWidth();
        int frameHeight = frame.getHeight();

        // 计算居中位置
        int x = (screenWidth - frameWidth) / 2;
        int y = (screenHeight - frameHeight) / 2;

        // 设置JFrame的位置
        frame.setLocation(x, y);

        frame.pack();
        frame.setVisible(true);
    }

    public CreateLicense() {
        shengchengButton.addActionListener(e -> {
            String mac = macTextField.getText().trim();
            String cpu = cpuTextField.getText().trim();
            String s = mac + "-" + cpu;
            String systemSign = AESUtils.encrypt(s);
            //JOptionPane.showMessageDialog(jpanel, systemSign);
            String area = areaTextField.getText().trim();
            String areaSign = AESUtils.encrypt(area);
            String generatedTimeStr = startTextField.getText().trim();
            String expiredTimeStr = endTextField.getText().trim();
            String lastValidateTimeStr = validateTextField.getText().trim();
            String version = versionTextField.getText().trim();
            String path = pathTextField.getText().trim();
            if ("".equals(mac) || "".equals(cpu) || "".equals(area) || "".equals(generatedTimeStr)
                    || "".equals(expiredTimeStr) || "".equals(lastValidateTimeStr)
                    || "".equals(version) || "".equals(path)) {
                JOptionPane.showMessageDialog(jpanel, "信息不能为空");
                return;
            }
            copySting(areaSign);
            JOptionPane.showMessageDialog(jpanel, "区划加密标识已自动复制，请注意保存：" + areaSign + "");
            createLicense(systemSign, area, generatedTimeStr, expiredTimeStr, lastValidateTimeStr, version, path);
            System.out.println("license文件生成成功，文件路径：" + path);
            JOptionPane.showMessageDialog(jpanel, "license文件生成成功，文件路径：" + path);
            String folderPath = "D:\\Desktop\\"; // 更改为你要打开的文件夹路径
            String fileName = "license.xml"; // 更改为你想选中的文件名
            int lastIndex = path.lastIndexOf('\\');
            if (lastIndex != -1) {
                folderPath = path.substring(0, lastIndex);
                fileName = path.substring(lastIndex + 1);
            }
            File file = new File(folderPath, fileName);
            if (file.exists()) {
                try {
                    // 使用 cmd.exe 运行命令，使用 start 命令打开文件夹并选中文件
                    // 注意：这个命令仅在Windows系统中有效
                    Runtime.getRuntime().exec(
                            "cmd.exe /c start \"\" /d \"" + folderPath + "\" explorer.exe /select,\"" + file.getAbsolutePath() + "\""
                    );
                } catch (IOException e1) {
                    System.err.println("无法打开文件夹并选中文件: " + e1.getMessage());
                }
            } else {
                System.err.println("指定的文件不存在");
            }
        });
        getMacButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String mac = getMacAddress();
                macTextField.setText(mac);
            }
        });
        getCpuButton.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                String cpu = getCpuNum();
                cpuTextField.setText(cpu);
            }
        });
        getAreaButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String area = generateRandomString(10);
                areaTextField.setText(area);
            }
        });
        chooseSDateButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                Dimension dialogSize = new Dimension(400, 250);
                Point screen = chooseSDateButton.getLocationOnScreen();
                Point point = new Point(screen.x, screen.y + chooseSDateButton.getPreferredSize().height + 5);

                Gqrq dateChooser = new Gqrq();
                String selectedDate = dateChooser.showDateDialog(new JFrame(), point, dialogSize);
                if (dateChooser.isConfirm()) {
                    startTextField.setText(selectedDate + " 00:00:00");
                    validateTextField.setText(selectedDate + " 00:00:00");
                }
            }
        });
        chooseEDateButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                Dimension dialogSize = new Dimension(400, 250);
                Point screen = chooseEDateButton.getLocationOnScreen();
                Point point = new Point(screen.x, screen.y + chooseEDateButton.getPreferredSize().height + 5);

                Gqrq dateChooser = new Gqrq();
                String selectedDate = dateChooser.showDateDialog(new JFrame(), point, dialogSize);
                if (dateChooser.isConfirm()) {
                    endTextField.setText(selectedDate + " 00:00:00");
                }
            }
        });
        chooseVDateButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                Dimension dialogSize = new Dimension(400, 250);
                Point screen = chooseVDateButton.getLocationOnScreen();
                Point point = new Point(screen.x, screen.y + chooseVDateButton.getPreferredSize().height + 5);

                Gqrq dateChooser = new Gqrq();
                String selectedDate = dateChooser.showDateDialog(new JFrame(), point, dialogSize);
                if (dateChooser.isConfirm()) {
                    validateTextField.setText(selectedDate + " 00:00:00");
                }
            }
        });
        getVersionButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                versionTextField.setText("0.0.1");
            }
        });
        getPathButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JFileChooser pathChooser = new JFileChooser();
                pathChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
                pathChooser.setMultiSelectionEnabled(false);
                pathChooser.setDialogTitle("选择文件路径");
                pathChooser.showOpenDialog(null);

                if (null == pathChooser.getSelectedFile()) {
                    return;//JOptionPane.showMessageDialog(jpanel, "请选择文件存放路径");
                } else {
                    String path = pathChooser.getSelectedFile().getPath();
                    pathTextField.setText(path + "\\license.xml");
                }

//                pathTextField.setText("D:\\Desktop\\license.xml");
            }
        });
    }

    private void createUIComponents() {
        // TODO: place custom component creation code here
    }

    public static String getMacAddress() {
        try {
            Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
            while (networkInterfaces.hasMoreElements()) {
                NetworkInterface networkInterface = networkInterfaces.nextElement();
                if (!networkInterface.isUp() || networkInterface.isLoopback() || networkInterface.isVirtual())
                    continue; // 忽略非活动、回环和虚拟接口
                byte[] mac = networkInterface.getHardwareAddress();
                if (mac != null) {
                    StringBuilder sb = new StringBuilder();
                    for (int i = 0; i < mac.length; i++) {
                        sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? ":" : ""));
                    }
                    return sb.toString(); // 返回MAC地址
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
        return "MAC address not found";
    }

    public static String getCpuNum() {
        try {
            //  Process process = Runtime.getRuntime().exec("wmic cpu get ProcessorID");
            String[] linux = {"/bin/bash", "-c", "dmidecode -t processor | grep 'ID' | awk -F ':' '{print $2}' | head -n 1"};
            String[] windows = {"wmic", "cpu", "get", "ProcessorId"};

            // 获取系统信息
            String property = System.getProperty("os.name");
            Process process = Runtime.getRuntime().exec(property.contains("Window") ? windows : linux);
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                if (!line.trim().isEmpty() && !line.trim().contains("ProcessorId")) {
                    //System.out.println("CPU序列号: " + line.trim());
                    reader.close();
                    return line.replaceAll(" ", "");
                }
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "CPU SerialNumber not found";
    }

    public static String generateRandomString(int length) {
        // 可选的字符集，包括大小写字母和数字
        String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        StringBuilder sb = new StringBuilder();
        Random random = new Random();

        for (int i = 0; i < length; i++) {
            // 随机选取字符集中的一个字符
            int index = random.nextInt(characters.length());
            char randomChar = characters.charAt(index);
            sb.append(randomChar);
        }

        return sb.toString();
    }

    public static void copySting(String textToCopy) {
        // 创建一个StringSelection对象
        StringSelection stringSelection = new StringSelection(textToCopy);
        // 获取系统剪贴板
        Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
        // 将StringSelection对象放到剪贴板上
        clipboard.setContents(stringSelection, null);
    }
}
